//
//  UIImage+LJ.swift
//  微信小视频
//
//  Created by 罗杰 on 2016/11/12.
//  Copyright © 2016年 罗杰. All rights reserved.
//

import Foundation
import UIKit
import AVFoundation
import CoreGraphics

extension UIImage {
    
    /// 从CMSampleBuffer获取一张UIImage
    ///
    /// - parameter sampleBuffer:
    ///
    /// - returns:
    class func imageWithSampleBuffer(sampleBuffer:CMSampleBuffer) ->UIImage {
        //    CMSampleBuffer被处理过的的媒体数据（audio, video, muxed, etc）
        
        let imageBuffer:CVImageBuffer? = CMSampleBufferGetImageBuffer(sampleBuffer)
        let flag = CVPixelBufferLockFlags(rawValue: CVOptionFlags())
        // 锁定 pixel buffer 的基地址
         CVPixelBufferLockBaseAddress(imageBuffer!, flag)
        // 得到 pixel buffer 的基地址
        let address:UnsafeMutableRawPointer? = CVPixelBufferGetBaseAddress(imageBuffer!)
        // 得到 pixel buffer 的行字节数
        let bytesPerRow:Int = CVPixelBufferGetBytesPerRow(imageBuffer!)
        
        // 得到 pixel buffer 的宽和高
        let width:Int = CVPixelBufferGetWidth(imageBuffer!)
        let height:Int = CVPixelBufferGetHeight(imageBuffer!)
        
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        
        let context = CGContext(data: address, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue)
        //bitMap的相关方法取消
        let imageRef = context!.makeImage()
        CVPixelBufferUnlockBaseAddress(imageBuffer!, CVPixelBufferLockFlags(rawValue: CVOptionFlags(0)))
        // 释放 context 和颜色空间.swift中CoreFoundation的对象自己管理内存
//        CGContextRelease(context!);
//        CGColorSpaceRelease(colorSpace);
        return UIImage.init(cgImage: imageRef!)
        
    }



}
